package com.gmrz.uaf.protocol.v1.processor;

import com.gmrz.uaf.common.Constants;
import com.gmrz.uaf.db.DAOException;
import com.gmrz.uaf.db.UAFDAOFactory;
import com.gmrz.uaf.db.UAFDBConnectionMgr;
import com.gmrz.uaf.db.dao.AuthenticatorDAO;
import com.gmrz.uaf.protocol.v1.processor.exception.*;
import com.gmrz.uaf.protocol.v1.schema.*;
import com.gmrz.util.db.DBUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

public class UAFRegStatusProcessor extends UAFBaseProcessor {
	private static final Logger LOG = LogManager.getLogger(UAFRegStatusProcessor.class);

	public List<List<String>> request(String userName, String appID,String deviceID,
								 List<String> authType,List<String> transType)
			throws DAOException {

		Connection conn = null;
		try {
			conn = UAFDBConnectionMgr.getConnection(true);
			AuthenticatorDAO dao = UAFDAOFactory.createAuthenticatorDAO(conn);

            List<List<String>> result = new ArrayList<List<String>>();

            // 查询认证数据
			List<Authenticator> authenticators = dao.findUserOnDevice(userName,appID,deviceID);
			for(String t : transType) {
				String applicationID = this.getServerConfig().getApplicationID(appID, t);
				if (this.getServerConfig().getTenantShare() && com.gmrz.util.Strings.isNotBlank(applicationID)) {
					List<String> shareAppIDList = getShareAppID(applicationID,t);
					for (String shareAppID : shareAppIDList) {
						List<Authenticator> shareAuthenticators = dao.findUserOnDevice(userName, shareAppID, deviceID);
						authenticators.addAll(shareAuthenticators);
					}
				}
			}
			//获取远程注册信息
			List<Authenticator> remoteAuthenticators = dao.findUserOnRemoteAuthType(userName,appID);
			authenticators.addAll(remoteAuthenticators);
//			if (this.getServerConfig().getTenantShare() && com.gmrz.util.Strings.isNotBlank(applicationID)) {
//				List<String> shareAppIDList = getShareAppID(applicationID);
//				for(String shareAppID : shareAppIDList){
//					List<Authenticator> shareAuthenticators = dao.findUserOnRemoteAuthType(userName,appID);
//					authenticators.addAll(shareAuthenticators);
//				}
//			}
//            //未注册任何认证方式
//			if(authenticators==null || authenticators.isEmpty()){
//                return result;
//			}
            boolean match = false;
            for(String aType:authType){
                List<String> status = new ArrayList<String>();
                for(String tType:transType){
					if(authenticators!=null && !authenticators.isEmpty()){
						for(Authenticator a:authenticators){
							if(tType.equals(a.getTransType()) && aType.equals(a.getAuthType())){
								match = true;
							}
						}
					}
                    status.add(match?"1":"0");
                    match=false;
                }
                result.add(status);
            }

            return result;
		}catch (SQLException se){
			LOG.error("Failed to access T_DEVICES data, ", se);
			throw new DAOException(UAFErrorCode.DB_DATABASE_CONNECTION_ERROR, se);
		}finally {
			DBUtil.close(conn);
		}
	}

	public long getCertAfterDate(String userName, String appID, String deviceID, String authType, String transType) throws DAOException {
		Connection conn = null;
		try {
			conn = UAFDBConnectionMgr.getConnection(true);
			AuthenticatorDAO dao = UAFDAOFactory.createAuthenticatorDAO(conn);

			long result = 0;

			Set<Authenticator> authenticators = dao.findUserOnDeviceDer( userName,  appID,  deviceID,  authType,  transType, Constants.AuthenticatorStatus.ACTIVE.getStatus());

			String applicationID = this.getServerConfig().getApplicationID(appID, transType);
			if (this.getServerConfig().getTenantShare() && com.gmrz.util.Strings.isNotBlank(applicationID)) {
				List<String> shareAppIDList = getShareAppID(applicationID,transType);
				for (String shareAppID : shareAppIDList) {
					Set<Authenticator> shareAuthenticators = dao.findUserOnDeviceDer( userName,  shareAppID,  deviceID,  authType,  transType, Constants.AuthenticatorStatus.ACTIVE.getStatus());
					authenticators.addAll(shareAuthenticators);
				}
			}
			if(null != authenticators && !authenticators.isEmpty()){
				Iterator<Authenticator> authenticatorIterator = authenticators.iterator();
				while (authenticatorIterator.hasNext()){
					Authenticator a = authenticatorIterator.next();
					result = a.getCertificateExtendBean().getExpireTime().getTime();
				}
			}
			return result;
		}catch (SQLException se){
			LOG.error("Failed to get certificate notaftertime error.", se);
			throw new DAOException(UAFErrorCode.DB_DATABASE_CONNECTION_ERROR, se);
		}finally {
			DBUtil.close(conn);
		}
	}

}
